package com.writing.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.writing.common.Result;
import com.writing.entity.Chapter;
import com.writing.entity.Novel;
import com.writing.service.ChapterService;
import com.writing.service.NovelService;
import lombok.RequiredArgsConstructor;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.List;
import java.util.Map;

/**
 * 章节控制器
 */
@RestController
@RequestMapping("/novels/{novelId}/chapters")
@RequiredArgsConstructor
public class ChapterController {

    private final ChapterService chapterService;
    private final NovelService novelService;

    /**
     * 验证用户是否有权限访问小说
     */
    private boolean validateNovelAccess(Long novelId, Long userId) {
        Novel novel = novelService.getById(novelId);
        return novel != null && novel.getUserId().equals(userId);
    }

    /**
     * 获取小说的所有章节
     */
    @GetMapping
    public Result<List<Chapter>> getChaptersByNovelId(@PathVariable Long novelId, HttpServletRequest request) {
        Long userId = (Long) request.getAttribute("userId");
        if (userId == null) {
            return Result.error("用户未登录");
        }

        // 验证权限
        if (!validateNovelAccess(novelId, userId)) {
            return Result.error("小说不存在或无权限访问");
        }

        try {
            List<Chapter> chapters = chapterService.getChaptersByNovelId(novelId);
            return Result.success(chapters);
        } catch (Exception e) {
            return Result.error("获取章节列表失败: " + e.getMessage());
        }
    }

    /**
     * 分页获取小说的章节列表
     */
    @GetMapping("/page")
    public Result<IPage<Chapter>> getChaptersByNovelIdWithPage(
            @PathVariable Long novelId,
            @RequestParam(defaultValue = "1") Integer current,
            @RequestParam(defaultValue = "10") Integer size,
            HttpServletRequest request) {
        Long userId = (Long) request.getAttribute("userId");
        if (userId == null) {
            return Result.error("用户未登录");
        }

        // 验证权限
        if (!validateNovelAccess(novelId, userId)) {
            return Result.error("小说不存在或无权限访问");
        }

        try {
            Page<Chapter> page = new Page<>(current, size);
            IPage<Chapter> chapters = chapterService.getChaptersByNovelIdWithPage(novelId, page);
            return Result.success(chapters);
        } catch (Exception e) {
            return Result.error("获取章节列表失败: " + e.getMessage());
        }
    }

    /**
     * 获取章节详情
     */
    @GetMapping("/{chapterId}")
    public Result<Chapter> getChapter(@PathVariable Long novelId,
                                    @PathVariable Long chapterId,
                                    HttpServletRequest request) {
        Long userId = (Long) request.getAttribute("userId");
        if (userId == null) {
            return Result.error("用户未登录");
        }

        // 验证权限
        if (!validateNovelAccess(novelId, userId)) {
            return Result.error("小说不存在或无权限访问");
        }

        try {
            Chapter chapter = chapterService.getChapterById(chapterId, novelId);
            if (chapter == null) {
                return Result.error("章节不存在");
            }
            return Result.success(chapter);
        } catch (Exception e) {
            return Result.error("获取章节详情失败: " + e.getMessage());
        }
    }

    /**
     * 创建章节
     */
    @PostMapping
    public Result<Chapter> createChapter(@PathVariable Long novelId,
                                       @RequestBody Chapter chapter,
                                       HttpServletRequest request) {
        Long userId = (Long) request.getAttribute("userId");
        if (userId == null) {
            return Result.error("用户未登录");
        }

        // 验证权限
        if (!validateNovelAccess(novelId, userId)) {
            return Result.error("小说不存在或无权限访问");
        }

        try {
            chapter.setNovelId(novelId);
            Chapter createdChapter = chapterService.createChapter(chapter);

            // 自动更新小说的章节数量和字数统计
            novelService.updateWordCount(novelId);

            return Result.success(createdChapter);
        } catch (Exception e) {
            return Result.error("创建章节失败: " + e.getMessage());
        }
    }

    /**
     * 更新章节
     */
    @PutMapping("/{chapterId}")
    public Result<Chapter> updateChapter(@PathVariable Long novelId,
                                       @PathVariable Long chapterId,
                                       @RequestBody Chapter chapter,
                                       HttpServletRequest request) {
        Long userId = (Long) request.getAttribute("userId");
        if (userId == null) {
            return Result.error("用户未登录");
        }

        // 验证权限
        if (!validateNovelAccess(novelId, userId)) {
            return Result.error("小说不存在或无权限访问");
        }

        try {
            chapter.setId(chapterId);
            chapter.setNovelId(novelId);
            Chapter updatedChapter = chapterService.updateChapter(chapter);
            if (updatedChapter == null) {
                return Result.error("章节不存在或无权限修改");
            }

            // 自动更新小说的章节数量和字数统计
            novelService.updateWordCount(novelId);

            return Result.success(updatedChapter);
        } catch (Exception e) {
            return Result.error("更新章节失败: " + e.getMessage());
        }
    }

    /**
     * 删除章节
     */
    @DeleteMapping("/{chapterId}")
    public Result<Void> deleteChapter(@PathVariable Long novelId,
                                    @PathVariable Long chapterId,
                                    HttpServletRequest request) {
        Long userId = (Long) request.getAttribute("userId");
        if (userId == null) {
            return Result.error("用户未登录");
        }

        // 验证权限
        if (!validateNovelAccess(novelId, userId)) {
            return Result.error("小说不存在或无权限访问");
        }

        try {
            boolean deleted = chapterService.deleteChapter(chapterId, novelId);
            if (!deleted) {
                return Result.error("章节不存在或无权限删除");
            }

            // 自动更新小说的章节数量和字数统计
            novelService.updateWordCount(novelId);

            return Result.success();
        } catch (Exception e) {
            return Result.error("删除章节失败: " + e.getMessage());
        }
    }

    /**
     * 更新章节顺序
     */
    @PutMapping("/order")
    public Result<Void> updateChapterOrder(@PathVariable Long novelId,
                                         @RequestBody List<Map<String, Object>> orderData,
                                         HttpServletRequest request) {
        Long userId = (Long) request.getAttribute("userId");
        if (userId == null) {
            return Result.error("用户未登录");
        }

        // 验证权限
        if (!validateNovelAccess(novelId, userId)) {
            return Result.error("小说不存在或无权限访问");
        }

        try {
            chapterService.updateChapterOrder(novelId, orderData);
            return Result.success();
        } catch (Exception e) {
            return Result.error("更新章节顺序失败: " + e.getMessage());
        }
    }
}
